/**
 * File: baidu_keywords.js
 * Author: James Tang<fwso@fwso.cn>
 * Date: 2010-08-18
 * (C) 2010 <a href="http://fwso.cn">Fwso.cn</a>. All Rights Reserved.
 */

/**
 * Class: BaiduKeywords Keywords Access Assistant.
 */
function BaiduKeywords() {

	this._init();

}

BaiduKeywords.instance = null;
BaiduKeywords.title = "BK Assistant 1.0 Beta";
BaiduKeywords.keepCount = false;

BaiduKeywords.fillKeyword = function(key) {
	$("#SearchInput").val(key);
	$("#SearchInputShow").val(key);
	$("#SearchBtn").click();
};

BaiduKeywords.getInstance = function() {

	if (!BaiduKeywords.instance) {
		BaiduKeywords.instance = new BaiduKeywords();
	}

	return BaiduKeywords.instance;
}

/**
 * @deprecated
 */
BaiduKeywords.doSearch = function() {

	// this.currentLevel = 0;

};

/**
 * <div id="jpanel"> <div id="jpanelHeader"> <div id="jpanelTitle"><span>BK
 * Assistant 1.0 Beta</span><a href="JavaScritp:void(0);" title="关闭">×</a></div>
 * <div id="optionBox"><form><input type="text" id="jKeyword" /><input
 * type="button" id="doStartButton" value="Start" /><input type="button"
 * id="getDataButton" value="Get Data" /></form></div> </div>
 * 
 * <div id="jpanelInnerBox"> <div id="keywordsBoxL" class="keywordsBox">
 * <ul id="levelOne">
 * </ul>
 * </div> <div id="keywordsBoxM" class="keywordsBox">
 * <ul id="levelTwo">
 * </ul>
 * </div> <div id="keywordsBoxR" class="keywordsBox">
 * <ul id="levelThree">
 * </ul>
 * </div> <div class="clear"></div> </div> </div>
 */
BaiduKeywords.prototype.initPanel = function() {

	// #initHTML
	$("#SearchInput").attr("readonly", "readonly");

	var _input = $("#PasvTabCnt p:first");

	var _html = '<div id="jpanel">';
	_html += '<div id="jpanelHeader">';
	_html += '<div id="jpanelTitle"><span>BK Assistant 1.0 Beta</span><a style="display:none;" href="JavaScritp:void(0);" title="关闭">×</a></div>';
	_html += '<div id="optionBox"><form id="jsearchForm"><div id="startInputBox"><input type="text" id="jKeyword" /><input type="button" id="doStartButton" value="Start" /></div><div id="doingBox" style="display:none;"><span id="motherKeyBox" style="font-weight:bold;"></span><input type="button" id="getDataButton" value="Get Data" /><input type="button" id="doNextButton" value="Next" /><input type="button" id="doExportButton" value="Export" /><input type="button" id="doCancelButton" value="Cancel" /></div></form></div>';
	_html += '</div>';
	_html += '<div id="jpanelInnerBox">';
	_html += '<div id="keywordsBoxL" class="keywordsBox"><ul id="levelOne"></ul></div>';
	_html += '<div id="keywordsBoxM" class="keywordsBox"><ul id="levelTwo"></ul></div>';
	_html += '<div id="keywordsBoxR" class="keywordsBox"><ul id="levelThree"></ul></div>';
	_html += '<div class="clear"></div>';
	_html += '</div>';
	_html += "</div>";

	$(_html).appendTo("body");
	// END#initHTML

	// initEvent
	var self = this;

	$("#doStartButton").click(function() {
		self._start();
	});

	$("#getDataButton").click(function() {
		self.getData();
	});

	$("#jsearchForm").submit(function() {
		self._start();
		return false;
	});

	$("#doCancelButton").click(function() {

		self._doCancel();

	});

	$("#doNextButton").click(function() {

		self._doNext();

	});

	$("#doExportButton").click(function() {

		self._doExport();

	});

	// END#initEvent

};

BaiduKeywords.overlay = function(data) {

	if ($("#exportKeywordsBox").length < 1) {

		$("body")
				.append(
						"<div id=\"overlay\"></div><div id=\"exportKeywordsBox\"><textarea id=\"textArea\">"
								+ data
								+ "</textarea><a href=\"JavaScript:void(0);\" id=\"closeOverlay\">关闭</a></div>");
		$("#overlay").css( {
			"height" : $(document).height() + "px"
		});

		var _box = $("#exportKeywordsBox");
		_box.css("left", parseInt(($(document).width() - _box.width()) / 2)
				+ "px");

		$("#closeOverlay").click(function() {
			$("#exportKeywordsBox").hide();
			$("#overlay").hide();
		});

	} else {
		$("#exportKeywordsBox").show();
		$("#textArea").val(data);
		$("#overlay").show();
	}
};

BaiduKeywords.prototype._doNext = function() {
	this._refresh_index();
	this._refresh_ui();
	window.console.log("NEXT#");
};

BaiduKeywords.prototype._doExport = function() {

	window.console.log("EXPORT#");

	var keys = "";

	for ( var i = 0; i < this.levelOne.length; i++) {

		if (this.keepCount) {
			keys += this.levelOne[i][0] + "\n";
		} else {
			keys += this.levelOne[i] + "\n";
		}
	}

	for ( var i = 0; i < this.levelTwo.length; i++) {

		if (this.keepCount) {
			keys += this.levelTwo[i][0] + "\n";
		} else {
			keys += this.levelTwo[i] + "\n";
		}
	}

	for ( var i = 0; i < this.levelThree.length; i++) {

		if (this.keepCount) {
			keys += this.levelThree[i][0] + "\n";
		} else {
			keys += this.levelThree[i] + "\n";
		}
	}

	window.console.log("KEYS#" + keys);

	BaiduKeywords.overlay(keys);
};

BaiduKeywords.prototype._init = function() {
	this.currentLevel = 0;
	this.levelOne = new Array();
	this.levelTwo = new Array();
	this.levelThree = new Array();
	this.motherWord = null;

	this.index = 0;
	this.key = null;
	this.node = null;
	this.switched = false;

	this.bkMinVisits = localStorage.bkMinVisits ? localStorage.bkMinVisits
			: 100;

	$(window).bind("beforeunload", function() {

		return "你正在离开该页面，如果确定离开，现有数据将自动清除";

	});
};

BaiduKeywords.prototype._doCancel = function() {

	if (confirm("确定要取消当前关键字?\n取消后当前数据将自动清除")) {
		$("#doingBox").hide();
		$("#startInputBox").show();
		$("#levelOne").html("");
		$("#levelTwo").html("");
		$("#levelThree").html("");
		this._init();
	}
};

BaiduKeywords.prototype._start = function() {

	this.currentLevel = -1;
	this.motherWord = $("#jKeyword").val();

	if (this.motherWord.length > 0) {

		window.console.log("Mother Keyword: " + this.motherWord);

		$("#motherKeyBox").html(this.motherWord);
		$("#doingBox").show();
		$("#startInputBox").hide();

		BaiduKeywords.fillKeyword(this.motherWord);
	}
};

BaiduKeywords.prototype._refresh = function() {
	BaiduKeywords.fillKeyword(this.key);
};

BaiduKeywords.prototype.getData = function() {

	window.console.log("Fetching data ...");

	var text = $("#KRTable .dataTable").html().trim();

	var pattern = /<label\s+for="kw_chkbox_[^>]*>(.*?)<\/label><\/td><td\s*[^>]*>[^\d]*([,\d]*)<\/td>/ig;

	window.console.log("DATA#" + text);

	var result = pattern.exec(text);

	if (text.length > 0 && result != null) {

		do {

			var visits = (result[2] && result[2].length > 0) ? parseInt(result[2]
					.replace(/(,|\s+)/ig, ""))
					: 0;

			if (result[1] && visits >= this.bkMinVisits) {

				var _item = result[1].replace(/<.*?>/ig, "");
				var item = null;

				if (BaiduKeywords.keepCount) {
					item = [ _item, visits ];
				} else {
					item = _item;
				}

				if (!item) {
					continue;
				}

				if (this.currentLevel <= 0
						&& _item.toLowerCase() != this.motherWord.toLowerCase()) {

					this.levelOne.push(item);

				} else if (this.currentLevel == 1) {

					if (this.levelOne.indexOf(item) == -1
							&& this.levelTwo.indexOf(item) == -1) {
						this.levelTwo.push(item);
					}

				} else if (this.currentLevel == 2) {
					if (this.levelOne.indexOf(item) == -1
							&& this.levelTwo.indexOf(item) == -1
							&& this.levelThree.indexOf(item) == -1) {
						this.levelThree.push(item);
					}
				}
			}

		} while ((result = pattern.exec(text)) != null);

		var _boxID = "levelOne";
		var keywords = new Array();

		if (this.currentLevel <= 0) {

			if (this.levelOne.length > 0) {
				keywords = this.levelOne;
			}

		} else if (this.currentLevel == 1) {

			_boxID = "levelTwo";
			keywords = this.levelTwo;

		} else if (this.currentLevel == 2) {

			_boxID = "levelThree";
			keywords = this.levelThree;

		}

		this._refresh_index();

		if (BaiduKeywords.keepCount) {
			keywords.sort(function(a, b) {
				return b[1] - a[1];
			});
		}

		var list = '';
		for ( var i = 0; i < keywords.length; i++) {

			if (BaiduKeywords.keepCount) {
				list += "<li class=\"waiting\">" + keywords[i][0] + "["
						+ keywords[i][1] + "]" + "</li>\n";
			} else {
				list += "<li class=\"waiting\">" + keywords[i] + "</li>\n";
			}
		}
		window.console.log("THIS.KEY#" + this.key);
		$("#" + _boxID).html(list);

		this._refresh_ui();

	} else {
		window.console.log("NO DATA FOUND#" + new Date().toString());
	}
};

/**
 * Refresh the current index(Move next);
 */
BaiduKeywords.prototype._refresh_index = function() {
	if (this.currentLevel <= 0) {

		if (this.levelOne.length > 0) {
			this.currentLevel = 1;
			this.key = this.levelOne[this.index];
			this.index++;
			this._refresh();
		}

	} else if (this.currentLevel == 1) {

		if (this.index < this.levelOne.length) {
			this.key = this.levelOne[this.index];
		} else {
			this.switched = true;
			this.currentLevel = 2;
			this.index = 0;
			this.key = this.levelTwo[this.index];
		}

		this.index++;
		this._refresh();

	} else if (this.currentLevel == 2) {

		if (this.index < this.levelTwo.length) {
			this.key = this.levelTwo[this.index];
			this.index++;
			this._refresh();
		}
	}
};

/**
 * Refresh the list view
 */
BaiduKeywords.prototype._refresh_ui = function() {
	var self = this;

	if (this.node == null) {

		this.node = $("#levelOne li:first").removeClass("waiting").addClass(
				"doing").bind("dblclick", function() {

			BaiduKeywords._try_request(self.key);

		}).css("cursor", "pointer");

	} else {

		this.node.removeClass("doing").addClass("done").unbind("dblclick").css(
				"cursor", "default");

		if (this.switched) {
			this.switched = false;
			this.node = $("#levelTwo li:first").removeClass("waiting")
					.addClass("doing");
		} else {
			this.node = this.node.next().removeClass("waiting").addClass(
					"doing");
		}

		this.node.bind("dblclick", function() {

			BaiduKeywords._try_request(self.key);

		}).css("cursor", "pointer");

		window.console.log("NODE#" + this.node.html());
	}
};

/**
 * Re-request of the current keyword
 */
BaiduKeywords._try_request = function(key) {

	window.console.log("RE-REQUEST#" + key);
	BaiduKeywords.fillKeyword(key);

};
